package com.ygou.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.noggit.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ygou.pojo.Admininfo;
import com.ygou.pojo.CountInfo;
import com.ygou.pojo.Goods;
import com.ygou.pojo.Ordergoods;
import com.ygou.pojo.Orders;
import com.ygou.pojo.Skus;
import com.ygou.pojo.UserAddress;
import com.ygou.pojo.Users;
import com.ygou.service.OrderGoodsService;
import com.ygou.service.OrdersService;
import com.ygou.service.SkusService;
import com.ygou.service.UserAddressService;
import com.ygou.utils.AppendContentToFile;
import com.ygou.utils.api.KdniaoTrackQueryAPI;
import com.ygou.utils.jedis.RedisUtil;

import net.sf.json.util.JSONUtils;

@Controller
@RequestMapping(value="/orders")
@SessionAttributes(value={"order","createTime","orderNo"})
public class OrdersController {
	
	@Autowired
	private OrdersService ordersService;
	@Autowired
	private OrderGoodsService orderGoodsService;
	@Autowired
	private UserAddressService userAddressSerive;
	@Autowired
	private SkusService skusService;
	/**
	 * 订单列表 条件 分页
	 * @param currPageNo
	 * @param pageSize
	 * @param orderNo
	 * @param createTime
	 * @param ispay
	 * @param isrefund
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/list")
	public String findlist(@RequestParam(value="currPageNo",defaultValue="1") Integer currPageNo,
			@RequestParam(value="pageSize",defaultValue="10") Integer pageSize,
			@RequestParam(value="orderNo",required=false) String orderNo,
			@RequestParam(value="createTime",required=false) String createTime,
			@RequestParam(value="ispay",required=false) Integer ispay,
			@RequestParam(value="isrefund",required=false) Integer isrefund,
			ModelMap model){
		PageHelper.startPage(currPageNo, pageSize);
		List<Orders> orders=ordersService.selectByExample(orderNo, createTime,ispay,isrefund);
		PageInfo<Orders> pages=new PageInfo<Orders>(orders,pageSize);
		model.put("pageInfo",pages);
		model.put("orderNo",orderNo==null?"":orderNo);
		model.put("createTime",createTime==null?"":createTime);
		return "/admin/Orderform";
	}
	
	/**
	 * 发货
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value="/updisrefund",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean updIsRefund(HttpSession session,Integer orderId){
		Orders orders=ordersService.selectByPrimaryKey(orderId);
		orders.setIssend((byte)1);
		orders.setDeliervytime(new java.util.Date());
		/*******写入日志******/
		Admininfo admin= (Admininfo)session.getAttribute("admin");
		int id=0;
		if(admin!=null){
			id=admin.getAdminid();
		}
		AppendContentToFile.fileLogPrint(id+"", "对订单编号为"+orders.getOrderno()+"进行了发货");
		/*******END写入日志******/
		return ordersService.updateByPrimaryKey(orders);
	}
	/**
	 * 确认收货
	 * @param orderid
	 * @return
	 */
	@RequestMapping(value="/takeover/{orderid}",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean takeover(@PathVariable Integer orderid){
		Orders order=ordersService.selectByPrimaryKey(orderid);
		order.setIstakeover((byte) 1);
		order.setReceivetime(new java.util.Date());
		return ordersService.updateByPrimaryKey(order);
	}
	/**
	 * 根据订单编号查询订单信息
	 * @param orderId
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/orderinfo/{orderId}")
	public String orderinfo(@PathVariable Integer orderId,ModelMap model) throws Exception{
		Ordergoods orderGoods=new Ordergoods();
		orderGoods.setOrderid(orderId);
		Orders order=ordersService.selectByPrimaryKey(orderId);
		List<Ordergoods> ogs=orderGoodsService.selectByExample(orderGoods);
		KdniaoTrackQueryAPI api = new KdniaoTrackQueryAPI();
		if(order.getIssend()==1){
			Map<String,Object> map=com.ygou.utils.JSONUtils.toHashMap(api.getOrderTracesByJson("ZTO", "479348241301"));
			model.put("logis",map);
		}
		model.put("order",order);
		model.put("ogs",ogs);
		
		return "/admin/order_detailed";
	}
	
	/**
	 * 统计报表 暂时
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/orderCount")
	public String orderCount(ModelMap model){
		Double totalMoney=ordersService.findSum(null);
		int orderCount=ordersService.countByExample(null);
		int successCount=ordersService.countByExample(0);
		int errorCount=ordersService.countByExample(1);
		Double refundMoney=ordersService.findSum("error");
		model.put("totalMoney", totalMoney);
		model.put("orderCount", orderCount);
		model.put("successCount", successCount);
		model.put("errorCount", errorCount);
		model.put("refundMoney", refundMoney);
		return "/admin/transaction";
	}
	
	@RequestMapping(value="/count",produces="application/json;charset=UTF-8")
	public @ResponseBody Map<String,Object> count(){
		return ordersService.count(null);
	}
	
	/**
	 * 前台根据订单编号查询订单信息
	 * @param orderId
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/findOrderByIdQ/{orderId}")
	public String findOrderByIdQ(@PathVariable Integer orderId,ModelMap model,HttpSession session){
		//Users user=(Users) session.getAttribute("user");
		Ordergoods orderGoods=new Ordergoods();
		orderGoods.setOrderid(orderId);
		Orders order=ordersService.selectByPrimaryKey(orderId);
		List<Ordergoods> ogs=orderGoodsService.selectByExample(orderGoods);
		List<UserAddress> address=userAddressSerive.findAddressByUId(order.getUserid());
		/*model.put("order",order);
		model.put("ogs",ogs);
		model.put("address",address);*/
		session.setAttribute("order",order);
		session.setAttribute("ogs",ogs);
		session.setAttribute("address",address);
		return "redirect:/order_details.jsp";
	}
	
	/**
	 * 购物车下单
	 * @param order
	 * @param cartids
	 * @return
	 */
	@RequestMapping(value="/addOrder")
	public String addOrder(Orders order,Integer[] cartids,HttpSession session){
		Users user=(Users) session.getAttribute("user");
		List<Integer> list=Arrays.asList(cartids);
		if(ordersService.addOrder(order, list,null,null)>0){
			return "redirect:/orders/findOrderByIdQ/"+order.getOrderid();
		}
		return "redirect:/cart/findCartByUId?userid="+user.getUserid();
	}
	/**
	 * 立即购买
	 * @param order
	 * @param goodsid
	 * @param skuattr
	 * @return
	 */
	@RequestMapping(value="/butNow",produces="application/json;charset=UTF-8")
	public @ResponseBody Integer butNow(Orders order,Integer goodsid,Integer skuattr){
		Skus sku=skusService.selectByPrimaryKey(skuattr);
		order.setTotalprice(sku.getPrice().multiply(new BigDecimal(order.getGoodcount())));
		int result=ordersService.addOrder(order,null,goodsid,skuattr);
		return result;
	}
	
	/**
	 * 订单结算
	 * @param orderid 订单编号
	 * @param userid 用户编号
	 * @return 结算状态
	 */
	@RequestMapping(value="/balance/{orderid}/{userid}",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean balance(@PathVariable Integer orderid,@PathVariable Integer userid){
		return ordersService.balance(orderid, userid);
	}
	/**
	 * 前台根据用户id获取订单列表
	 * @param userid
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/getorder/{userid}")
	public String getOrders(@PathVariable Integer userid,ModelMap model){
		List<Orders> orders=ordersService.getOrdersQ(userid);
		model.put("orders",orders);
		return "order";
	}
	
	/**
	 * 删除订单
	 * @param orderid 订单编号
	 * @return
	 */
	@RequestMapping(value="/delOrder/{orderid}",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean delOrder1(HttpSession session,@PathVariable Integer orderid){
		/*******写入日志******/
		Admininfo admin= (Admininfo)session.getAttribute("admin");
		int id=0;
		if(admin!=null){
			id=admin.getAdminid();
		}
		AppendContentToFile.fileLogPrint(id+"", "管理员删除了订单");
		/*******END写入日志******/
		return ordersService.delOrder(orderid);
	}
	
	/**
	 * 用户中心获取订单详情
	 * @param orderid
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/getOrderByInfo/{orderid}")
	public String getOrderByInfo(@PathVariable Integer orderid,
			@RequestParam(defaultValue="0") Integer type,
			HttpSession session,ModelMap model) throws Exception{
		Users user=(Users) session.getAttribute("user");
		Orders order=ordersService.selectByPrimaryKey(orderid);
		if(order!=null){
			/*session.removeAttribute("order");
			session.setAttribute("order", order);*/
			if(order.getIssend()==1){
				KdniaoTrackQueryAPI api = new KdniaoTrackQueryAPI();
				Map<String,Object> map=com.ygou.utils.JSONUtils.toHashMap(api.getOrderTracesByJson("ZTO", "479348241301"));
				model.put("logis",map);
			}
			model.put("order", order);
			if(type==0){
				return "orderinfo";
			}else{
				return "refund";
			}
			
		}
		return "redirect:/getorder/"+user.getUserid();
	}
}